package com.zheng.api.server.controller;

import com.zheng.api.server.service.ApiServerPayService;
import com.zheng.common.constant.PayConstant;
import com.zheng.upms.rpc.api.UpmsSystemParamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;

/**
 * @Description: 接收处理支付宝通知
 * @author lvb
 * @date 2017-07-05
 * @version V1.0
 * @Copyright:
 */
@Controller
@Api(value = "支付宝支付回调通知控制器", description = "支付宝支付回调通知控制器")
@RequestMapping("/v1/pay")
public class ApiPayNotify4AliController {

	private static final Logger LOGGER = LoggerFactory.getLogger(ApiPayNotify4AliController.class);

	@Autowired
	private ApiServerPayService apiServerPayService;
	@Autowired
	UpmsSystemParamService upmsSystemParamService;

	/**
	 * 支付宝移动支付后台通知响应
	 * @param request
	 * @return
	 * @throws ServletException
	 * @throws IOException
     */
	@RequestMapping(value = "/notify/aliPayNotifyRes.htm")
	@ApiOperation(value = "支付宝支付回调通知")
	@ResponseBody
	public String aliPayNotifyRes(HttpServletRequest request) throws ServletException, IOException {
		LOGGER.info("====== 开始接收支付宝支付回调通知 ======");
		String notifyRes = doAliPayRes(request);
		LOGGER.info("响应给支付宝:{}", notifyRes);
		LOGGER.info("====== 完成接收支付宝支付回调通知 ======");
		return notifyRes;
	}

	private String doAliPayRes(HttpServletRequest request) throws ServletException, IOException {
		String logPrefix = "【支付宝支付回调通知】";
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		LOGGER.info("{}通知请求数据:reqStr={}", logPrefix, params);
		if(params.isEmpty()) {
			LOGGER.error("{}请求参数为空", logPrefix);
			return PayConstant.RETURN_ALIPAY_VALUE_FAIL;
		}

		String isForward = upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_PAYORDER_TEST_FORWARD_ENABLE");
		if("true".equals(isForward)){
			String orderprefix = upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_PAYORDER_TEST_FORWARD_PREFIX");
			String out_trade_no = params.get("out_trade_no");			// 商户系统订单号
			if(out_trade_no!=null && orderprefix!=null && out_trade_no.startsWith(orderprefix)){
				String forward_address = upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_PAYORDER_TEST_FORWARD_ALINOTIFYADDRESS");
				HttpPost httpPost = null;
				try {
					HttpClient httpClient = new DefaultHttpClient();
					httpPost = new HttpPost(forward_address);
					List<NameValuePair> list = new ArrayList<NameValuePair>();
					for (String key : params.keySet()) {
						list.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
					}
					//将参数进行编码为合适的格式,如将键值对编码为param1=value1&param2=value2
					UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "utf-8");
					httpPost.setEntity(urlEncodedFormEntity);
					HttpResponse httpResponse = httpClient.execute(httpPost);
					int statusCode = httpResponse.getStatusLine().getStatusCode();
					if (statusCode == HttpStatus.SC_OK) {
						HttpEntity resEntity = httpResponse.getEntity();
						if (resEntity != null) {
							String ret = EntityUtils.toString(resEntity, Charset.forName("utf-8"));
							return ret;
						}
					}
				} catch (Exception e) {
					LOGGER.error("转发测试环境异常",e);
				} finally {
					if (httpPost != null) {
						httpPost.releaseConnection();
					}
				}
				return null;
			}else{
				return apiServerPayService.doAliPayNotify(params);
			}
		}
		return apiServerPayService.doAliPayNotify(params);
	}
	
}
